package services.managers;

import bbdd.Conexion;
import bean.BeanSession;
import model.app.Menu;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by juanky on 8/12/14.
 */
public class MenuManager {
    public List<Menu> getMenu(BeanSession bean) {
        List<Menu> elementosMenu = new ArrayList();
        Conexion cnx = new Conexion();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String select = "select m.id, m.titulo, m.accion " +
                "from menu m, rel_menu_roles r " +
                "where m.padre is null and r.menu=m.id and r.rol=? order by m.orden";
        try {
            ps = cnx.getConexion(select);
            ps.setInt(1, bean.getRolId());
            rs = ps.executeQuery();
            while (rs.next()) {
                Menu menu = new Menu();
                menu.setId(rs.getInt("id"));
                menu.setTitulo(rs.getString("titulo"));
                menu.setAccion(rs.getString("accion"));
                menu.setHijos(this.getHijos(menu.getId(), bean));
                elementosMenu.add(menu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Conexion.close(cnx, ps, rs);
        }
        return elementosMenu;
    }

    private List<Menu> getHijos(Integer id, BeanSession bean) {
        List elementosMenu = new ArrayList();
        Conexion cnx = new Conexion();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String select = "select m.id, m.titulo, m.accion " +
                "from menu m, rel_menu_roles r " +
                "where m.padre=? and r.menu=m.id and r.rol=? order by m.orden";
        try {
            ps = cnx.getConexion(select);
            ps.setInt(1, id);
            ps.setInt(2, bean.getRolId());
            rs = ps.executeQuery();
            while (rs.next()) {
                Menu menu = new Menu();
                menu.setId(rs.getInt("id"));
                menu.setTitulo(rs.getString("titulo"));
                menu.setAccion(rs.getString("accion"));
                menu.setHijos(this.getHijos(menu.getId(), bean));
                elementosMenu.add(menu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Conexion.close(cnx, ps, rs);
        }
        return elementosMenu;
    }
}
